//
//  FileCacheManager.m
//  first app
//
//  Created by 林 小明 on 14-7-10.
//
//

#import "FileCacheManager.h"
#import "FileCache.h"
#import "FileCenter.h"
#import "ContentParseCenter.h"

@implementation FileCacheManager

static NSString* kCachePath = @"cache";

+ (FileCacheManager *)sharedSingleton
{
    static FileCacheManager *sharedSingleton;
    
    @synchronized(self)
    {
        if (!sharedSingleton)
            sharedSingleton = [[FileCacheManager alloc] init];
        
        return sharedSingleton;
    }
}

- (FileCacheManager *)init
{
    downloadingSet = [[NSMutableSet alloc]initWithCapacity:20];
    return [super init];
}

- (void)refreshCacheFile:(NSString*)url FileName:(NSString*)filename Force:(BOOL)force
{
    if( ![downloadingSet containsObject:filename] )
    {
        [downloadingSet addObject:filename];
    
        BOOL needRefresh = NO;
    
        if ( [FileCenter IsFileExistInDocuments:kCachePath fileName:[NSString stringWithFormat:@"%@.html",filename]] )
        {
            NSDictionary* fileAttr = [FileCenter GetDocumentsFileAttribute:kCachePath fileName:[NSString stringWithFormat:@"%@.html",filename]];
     
            NSDate *fileModDate = [fileAttr objectForKey:NSFileModificationDate];
        
            NSDate *now = [NSDate date];

            NSTimeInterval secondsBetweenDates= [now timeIntervalSinceDate:fileModDate];
            NSLog(@"secondsBetweenDates = %lf", secondsBetweenDates);
            if ( secondsBetweenDates > 3600 )
            {
                needRefresh = YES;
            }
        }
        else
        {
            needRefresh = YES;
        }
    
        if( force || needRefresh )
        {
            NSMutableURLRequest *URLRequest = [
                                           [NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10 ];
        
            [URLRequest setHTTPMethod:@"GET"];
        
            //NSURLConnection* connection = [[NSURLConnection alloc]initWithRequest:URLRequest delegate:self];
        
            //if (connection != nil) {
            //    //NSLog(@"connection ok");
            //}else{
            //    NSLog(@"connection fail");
            //}
        
            NSData *returnData = [NSURLConnection sendSynchronousRequest:URLRequest returningResponse:nil error:nil];
        
            NSString* htmlContent = [[NSString alloc] init];
            htmlContent = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
        
            NSLog(@"http get size:[%lu]", (unsigned long)[htmlContent length] );
        
            FileCache* fileCache = [[FileCache alloc]initWithData:[ContentParseCenter parseContent:htmlContent]];
            
            NSData* fileCacheData = [NSKeyedArchiver archivedDataWithRootObject:fileCache];
            
            [FileCenter CreateDocumentsDirectory:kCachePath];
            [FileCenter SaveToFile:kCachePath fileName:[NSString stringWithFormat:@"%@.html",filename] fileData:fileCacheData fileOffset:0];
        }
        
        [downloadingSet removeObject:filename];
    }
    NSMutableDictionary *refreshResult = [[NSMutableDictionary alloc] initWithCapacity:20];
    [refreshResult setValue:filename forKey:@"filename"];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"Notification_RefreshCache" object:refreshResult userInfo:nil];
}

- (NSMutableArray*)getContentFromCacheFile:(NSString*)filename
{
    NSMutableArray* titleIndex = [[NSMutableArray alloc] init];
    
    if ( [FileCenter IsFileExistInDocuments:kCachePath fileName:[NSString stringWithFormat:@"%@.html",filename]] )
    {
        //htmlContent = [FileCenter ReadStringFile:kCachePath fileName:[NSString stringWithFormat:@"%@.html",filename]];
        NSData* fileCacheData = [FileCenter ReadFile:kCachePath fileName:[NSString stringWithFormat:@"%@.html",filename]];
        
        FileCache *fileCache = [NSKeyedUnarchiver unarchiveObjectWithData:fileCacheData];
        titleIndex = [fileCache getContent];
    }
    
    return titleIndex;
}

@end
